const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,
    meeting: {},
    typeArray: ['起重器械', '压力容器', '锅炉', '压力管道', '叉车', '电梯','安全阀','压力表'],
    typeArrayName:"", //设备名
    equipmentType:'',
    typeArraySearchList:[],
    typeIndex: null,
    evaluateArray: ['安全风险可控,无较大安全风险隐患','存在安全风险隐患,需尽快采取防范措施','存在严重安全风险隐患,需尽快采取防范措施,请公司负责人重视'],
    evaluateIndex: null,
    equipmentTypebigSearchShow:false,
    id: null,
    deptList: [],
    imgList: [],
    convenerDept: "",
    searchDataList: [],
    meetDate: new Date().toISOString().substring(0, 10),
    user: wx.getStorageSync('userinfo').siocCnName,
    depts: [],
    deptIndex: null
  },
  deptChange: function (e) {
    this.setData({
      deptIndex: e.detail.value
    })
  },
  typeChange: function (e) {
    this.setData({
      typeIndex: e.detail.value
    })
  },
  evaluateChange(e){
    this.setData({
      evaluateIndex: e.detail.value
    })
  },

  getMeetingDetail: function (id) {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/seMonthlyMeeting/wx/' + id,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取月度会议详情:', res.data);
        var data = res.data;
        const tempArray = []
        data.data?.equipmentType?.split(',')?.forEach(item=>{
          tempArray.push(that.data.typeArray[item])
        })
        that.setData({
          meeting: data.data,
          typeIndex: data.data.equipmentType,
          typeArrayName:tempArray.join(','),
          meetDate: data.data.meetDate,
          id: data.data.id,
          convenerDept: data.data.convenerDept,
          imgList: data.data.imgList
        });
      }
    });
  },

  submitForm(e) {
    var that = this;
    
    const formData = e.detail.value;
    // formData.convenerDept = that.data.convenerDept;
    formData.equipmentType = that.data.equipmentType;

    formData.imgList = that.data.imgList;
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    var errMsg = "";
    if (!formData.equipmentType) {
      errMsg = errMsg + "设备类型不能为空;";
    }
    if (!formData.convener) {
      errMsg = errMsg + "召集人不能为空;";
    }
    if (!formData.convenerDept) {
      errMsg = errMsg + "召集部门不能为空;";
    }
    if (!formData.participant) {
      errMsg = errMsg + "参与人不能为空;";
    }
    if (!formData.workReport) {
      errMsg = errMsg + "本月安全管理工作情况汇报不能为空;";
    }
    if (!formData.riskReport) {
      errMsg = errMsg + "本月安全日常管理,风险隐患排查治理情况工作总结不能为空;";
    }
    if (!formData.workPlan) {
      errMsg = errMsg + "下个月工作安排不能为空;";
    }
    if (errMsg.length > 0) {
      wx.showModal({
        title: '提示',
        content: errMsg,
        showCancel: false
      })
      return;
    }
    // 向服务器提交表单数据
    wx.request({
      url: that.data.baseUrl + '/seMonthlyMeeting/wx/add',
      method: 'POST',
      data: formData,
      success: function (res) {
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/se-meeting-list/se-meeting-list'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });

  },

  DateChange: function (e) {
    this.setData({
      meetDate: e.detail.value
    })
  },

  getAllDept: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/deptInfo/wx/getAllDept',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取所有部门信息:', res.data);
        var data = res.data;
        that.setData({
          deptList: data.data
        })
      }
    });
  },

  doequipmentTypeBigSearchShow(e){
    const tempArray = this.data.typeArray.map(item=> {return {name: item}}) 
    this.setData({
      equipmentTypebigSearchShow: true,
      typeArraySearchList:tempArray
    })
  },

  doBigSearchShow(e) {
    console.log('e', e);
    const tempArray = [];
    const typeMethods = {
      dept: () => {
        if (this.data.deptList.length == 0) {
          wx.showToast({
            title: '暂无部门',
            icon: 'none'
          });
          return;
        } else {
          this.data.deptList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      }
    }
    typeMethods[e.currentTarget.dataset.type]();

    this.setData({
      bigSearchType: e.currentTarget.dataset.type,
      bigSearchShow: true,
      searchDataList: tempArray
    })
  },
  searchSelect(e) {
    const params = {}
    params['convenerDept'] = e.detail.name

    this.setData({
      ...params
    })
  },
  ViewImage(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    for (let key in this.data.imgList) {
      urls.push(this.data.fileUrl + this.data.imgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.imgList.length != 0) {
              that.setData({
                imgList: that.data.imgList.concat(tempArray)
              })
            } else {
              that.setData({
                imgList: tempArray
              })
            }
          }
        })
      }
    })
  },

  getSeDept: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/seWeeklyCheck/wx/getSeDept',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取特种设备部门:', res.data);
        var data = res.data;
        that.setData({
          depts: data.data
        });
      }
    });
  },

  equipmentTypeSearchSelect(e){

    if(e.detail.length>0){
      const tempArray =  []
      const tempArray1 =  []
      e.detail.forEach(item=>{
        tempArray.push(this.data.typeArray.findIndex((subitem)=> subitem==item.name))
        tempArray1.push(item.name)
      })

      this.setData({
        equipmentType: tempArray.join(','),

        typeArrayName:tempArray1.join(',')
    })
    }
    // const params = {}
    // params['convenerDept'] = e.detail.name

    // this.setData({
    //   ...params
    // })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getAllDept();
    this.getSeDept();
    console.log('options', options);
    if(options.id){
      this.getMeetingDetail(options.id);
      this.setData({
        id: options.riskId
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})